import styles from '../../index.less';
import { useUnmount } from '@umijs/hooks';
import React, { useEffect, useMemo, memo } from 'react';
import { Row, Col, message, Menu, Upload, Popconfirm, Dropdown, Button } from 'antd';
import useModel from '../../useModels/useModel.js';
import MessageModal from './messageModal.js';
import EmptyCenter from '@/components/EmptyCenter';
import classnames from 'classnames';
import VendorEdit from './VendorEdit';
import FlowMenuBox from './FlowMenuBox';
import useFlowModel from '../../useModels/useFlowModel';
import useMonitoringModel from '../../useModels/useMonitoringModel';

//table列表
export default memo(() => {
  const model = useModel(model => [model.state.data]);
  const { run, clear, customProps } = model;
  const { getFlowList } = useFlowModel(model => []);
  const {
    data: { dataList = [] },
  } = model.state;

  useEffect(() => {
    let row = {};
    if (localStorage.getItem('deviceType')) {
      row = JSON.parse(localStorage.getItem('deviceType'));
    }
    if (row?.id) {
      run({ pageSize: 9999, currentPage: 1, fsuTypeId: row.id });
      //
      const params = { fsuTypeId: row.id };
      customProps.run(params);
      getFlowList(params);
    }
  }, []);
  useUnmount(() => {
    clear();
  });

  return useMemo(() => {
    return (
      <div className={styles['table-wrap']}>
        <Row className={styles['table-thead']}>
          <Col span={2} className={styles['th']}>
            序号
          </Col>
          <Col span={6} className={styles['th']}>
            FSU设备名称
          </Col>
          <Col span={6} className={styles['th']}>
            厂商
          </Col>
          <Col span={10} className={styles['th']}>
            操作
          </Col>
        </Row>
        <div
          className={classnames(
            styles['table-tbody'],
            ((dataList && !dataList[0]) || !dataList) && styles['empty-wrap'],
          )}
        >
          {((dataList && !dataList[0]) || !dataList) && <EmptyCenter />}
          {(dataList || []).map((item, index) => {
            return <TableRow key={index.toString(36) + index} item={item} index={index} />;
          })}
        </div>
        <MessageModal />
      </div>
    );
  }, [dataList]);
});

const menu = item => {
  const {
    state: { customAllList },
    getCustomParams,
    setState,
  } = useModel(model => [model.state.customAllList]);
  const list = customAllList.filter(app => {
    return app.name !== 'main' && app.msgType === 1;
  });

  const handleMenuClick = (e, item) => {
    if (e.key === 'none') {
      message.error('该设备暂无报文，请移步添加报文!');
      return;
    }

    const current = customAllList.filter(item => {
      return item.id == e.key;
    });
    getCustomParams({ customIndex: current[0].id, suIndex: item.id });
    setState({ visible: true, customMessageData: current[0], suItemData: item });
  };

  return (
    <Menu
      onClick={e => {
        handleMenuClick(e, item);
      }}
      className={styles['menu-custom-height']}
    >
      {list.map(item => {
        return <Menu.Item key={item.id}>{item.name}</Menu.Item>;
      })}
      {!list[0] && (
        <Menu.Item key={'none'} className={styles['no-data']}>
          {'暂无报文'}
        </Menu.Item>
      )}
    </Menu>
  );
};

const TableRow = ({ item, index }) => {
  const { updateInfoProps, setState, deleteSuProps, detectionhttp } = useModel(model => [
    model.detectionhttp,
  ]);
  const { setMonitorState, getMonitorData } = useMonitoringModel(model => [model.getMonitorData]);
  function PrefixZero(num, n) {
    return (Array(n).join(0) + num).slice(-n);
  }
  const uploadProps = {
    name: 'files',
    action: '/api/telecom/upload',
    data: { suId: item.suId },
    showUploadList: false,
    multiple: true,
    accept: 'text/xml,application/xml',
    onChange(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        message.success(`${info.file.name}文件上传成功.`);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name}文件上传失败.`);
      }
    },
  };

  return (
    <Row className={styles['table-tbody-tr']}>
      <Col span={2} className={styles['tr-name']}>
        <span className={styles['num']}>{PrefixZero(index + 1, 2)}</span>
      </Col>
      <Col span={6} className={styles['tr-name']}>
        <span className={styles['name']}>{item.suId}</span>
      </Col>
      <Col span={6} className={styles['tr-name']}>
        <span className={styles['name']}>
          <VendorEdit item={item} updateInfoProps={updateInfoProps} />
        </span>
      </Col>
      <Col span={10} className={styles['operation']}>
        <span className={styles['flow']}>
          <FlowMenuBox item={item} />
        </span>
        <span
          className={styles['monitoring']}
          onClick={() => {
            setMonitorState({ monitoringVisible: true, suItemData: item });
            getMonitorData(item);
          }}
        >
          <Button>监控</Button>
        </span>
        <span className={styles['rest']}>
          <Dropdown overlay={menu(item)} placement="bottomLeft" trigger={'click'}>
            <Button>下发</Button>
          </Dropdown>
        </span>
        <span className={styles['upload']}>
          <Upload {...uploadProps} className={styles['upload-wrap']}>
            <Button>上传</Button>
          </Upload>
        </span>
        <span
          className={styles['rest']}
          onClick={() => {
            detectionhttp({
              suIndex: item.id,
            });
          }}
        >
          <Button>检测</Button>
        </span>
        {/* <span
          className={styles['result']}
          onClick={() => {
            setState({ singleData: item, resultVisible: true });
          }}
        >
          <Button>日志</Button>
        </span> */}
        <span className={styles['delete']}>
          <Popconfirm
            title="确定要删除此设备吗？"
            onConfirm={() => {
              deleteSuProps.run({ id: item.id });
            }}
            okText="确定"
            cancelText="取消"
          >
            <Button>删除</Button>
          </Popconfirm>
        </span>
      </Col>
    </Row>
  );
};
